package com.core.image.core.impl;

import com.core.image.core.Connector;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * describe:
 *
 * @author 库琦
 * @date 2020/02/05/22:08
 */
public abstract class ScheduleJob implements  Runnable {
    protected final long idleTimeMilliseconds;
    protected final Connector connector;
    protected volatile  Scheduler scheduler;
    //调度任务时返回的Future用以取消操作
    private volatile ScheduledFuture scheduledFuture;
    public  ScheduleJob(long idleTime, TimeUnit timeUnit,Connector connector){
        this.idleTimeMilliseconds = timeUnit.toMillis(idleTime);
        this.connector =connector;
    }

    /**
     * 调度当前任务
     * @param scheduler
     */
   public synchronized  void schedule(Scheduler scheduler){
        this.scheduler = scheduler;
        schedule(idleTimeMilliseconds);
    }
    public  synchronized void unSchedule(){
        if (scheduler != null){
            scheduler = null;
        }
        if (scheduledFuture != null){
            scheduledFuture.cancel(true);
            scheduledFuture = null;

        }

    }

    /**
     * 调度当前任务的具体实现
     * @param idleTimeMilliseconds 等待毫秒
     */
    public synchronized  void schedule(long idleTimeMilliseconds){
        if (scheduler != null){
            scheduledFuture = scheduler.schedule(this, idleTimeMilliseconds, TimeUnit.MILLISECONDS);
        }

    }


}
